package com.getpebble.android.framework.connectionstate;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.bluetooth.device.ConnectionResult;
import com.getpebble.android.common.core.trace.Analytics.RemoteDeviceInterface;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.model.ConnectionGoal;
import com.getpebble.android.common.model.ConnectionStatus;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.model.PblDeviceModel;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.common.model.PblDeviceModel.Query;
import com.getpebble.android.framework.DeviceInterfaces.IAdapterQuery;
import com.getpebble.android.framework.DeviceInterfaces.IAdapterQueryCallback;
import com.getpebble.android.framework.DeviceInterfaces.IDeviceConnector;
import com.getpebble.android.framework.DeviceInterfaces.IDeviceConnectorCallback;
import com.getpebble.android.framework.DeviceInterfaces.IDeviceMessageSender;
import com.getpebble.android.framework.comm.MessageRouter;
import com.getpebble.android.framework.connectionstate.ConnectionStateInterfaces.IHandshakeResult;
import com.getpebble.android.framework.endpoint.HandshakeEndpointSet;
import com.sun.mail.iap.Response;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConnectionStateManager extends BroadcastReceiver implements IAdapterQueryCallback, IDeviceConnectorCallback, IHandshakeResult {
    static final long[] BACKOFF_PERIODS_MILLIS = new long[]{1000, 2000, 4000, 8000, 32000, 64000, 128000, 256000, 512000, 900000};
    private static final String PACKAGE_NAME = PebbleApplication.getAppContext().getPackageName();
    private static final String TAG = ConnectionStateManager.class.getSimpleName();
    private boolean mBTAdapterEnabled;
    private final IAdapterQuery mBtAdapter;
    private final IDeviceConnector mBtConnection;
    private final IDeviceMessageSender mBtMessage;
    private final ConnectionGoalUpdater mConnectionGoalUpdater;
    private final PublicConnectionStatusUpdater mConnectionStatusUpdater;
    private final Context mContext;
    private PendingIntent mCurrentAlarmIntent;
    private final Map<PblDevice, PrivateState> mDeviceToPrivateStateMap = new HashMap();
    private final FrameworkState mFrameworkState;
    private final Handler mHandler;
    private boolean mMultipleHandshakeFailures;
    private Runnable sBackoffRunnable = new Runnable() {
        public void run() {
            Trace.debug(ConnectionStateManager.TAG, "sBackoffRunnable firing");
            ConnectionStateManager.this.cancelBackoffCallbacks();
            ConnectionStateManager.this.processState(false);
        }
    };

    static /* synthetic */ class AnonymousClass2 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$bluetooth$device$ConnectionResult = new int[ConnectionResult.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState = new int[PrivateConnectionState.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$bluetooth$device$ConnectionResult[ConnectionResult.SUCCESS.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$bluetooth$device$ConnectionResult[ConnectionResult.NOT_AVAILABLE.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$bluetooth$device$ConnectionResult[ConnectionResult.TIMEOUT.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$bluetooth$device$ConnectionResult[ConnectionResult.NOT_BONDED.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState[PrivateConnectionState.DISCONNECTED.ordinal()] = 1;
            } catch (NoSuchFieldError e5) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState[PrivateConnectionState.CONNECTING.ordinal()] = 2;
            } catch (NoSuchFieldError e6) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState[PrivateConnectionState.BACKOFF.ordinal()] = 3;
            } catch (NoSuchFieldError e7) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState[PrivateConnectionState.LINK_ESTABLISHED.ordinal()] = 4;
            } catch (NoSuchFieldError e8) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState[PrivateConnectionState.HANDSHAKE_INITIATED.ordinal()] = 5;
            } catch (NoSuchFieldError e9) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState[PrivateConnectionState.HANDSHAKE_FAILED.ordinal()] = 6;
            } catch (NoSuchFieldError e10) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState[PrivateConnectionState.CONNECTED.ordinal()] = 7;
            } catch (NoSuchFieldError e11) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState[PrivateConnectionState.CONNECTED_PRF.ordinal()] = 8;
            } catch (NoSuchFieldError e12) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState[PrivateConnectionState.DISCONNECTING.ordinal()] = 9;
            } catch (NoSuchFieldError e13) {
            }
        }
    }

    public static class ConnectionGoalUpdater {
        private final ContentResolver mContentResolver;

        public ConnectionGoalUpdater(ContentResolver contentResolver) {
            this.mContentResolver = contentResolver;
        }

        void onConnectionGoalUpdated(PblDevice device, ConnectionGoal goal) {
            ContentValues updatedValues = new ContentValues(1);
            updatedValues.put("connection_goal", Integer.valueOf(goal.getIntValue()));
            PblDeviceModel.updateDevice(this.mContentResolver, device, updatedValues);
        }
    }

    private enum PrivateConnectionState {
        DISCONNECTED,
        CONNECTING,
        BACKOFF,
        LINK_ESTABLISHED,
        HANDSHAKE_INITIATED,
        HANDSHAKE_FAILED,
        CONNECTED,
        CONNECTED_PRF,
        DISCONNECTING
    }

    private class PrivateState {
        private long mBackoffExpiryTimeMillis;
        private boolean mBackoffInitiated;
        private int mBackoffPeriodIndex;
        private Runnable mDelayedPublicDisconnectUpdateRunnable;
        private PblDevice mDeviceHandle;
        private MessageRouter mMessageRouter;
        private ConnectionGoal mPrivateGoal;
        private PrivateConnectionState mPrivateState;
        private ConnectionStatus mPublicState;
        private ConnectionStatus mPublishedPublicState;
        private boolean mReconnectGracePeriodActive;

        private PrivateState(PblDevice handle) {
            this.mPrivateState = PrivateConnectionState.DISCONNECTED;
            this.mPrivateGoal = ConnectionGoal.DISCONNECT;
            this.mPublicState = ConnectionStatus.DISCONNECTED;
            this.mPublishedPublicState = ConnectionStatus.DISCONNECTED;
            this.mBackoffInitiated = false;
            this.mReconnectGracePeriodActive = false;
            this.mDelayedPublicDisconnectUpdateRunnable = new Runnable() {
                public void run() {
                    Trace.debug(ConnectionStateManager.TAG, "disconnection grace period ending for " + PrivateState.this.mDeviceHandle);
                    PrivateState.this.mReconnectGracePeriodActive = false;
                    PrivateState.this.setPublicState();
                }
            };
            this.mDeviceHandle = handle;
            this.mMessageRouter = MessageRouter.getOrCreateRouter(ConnectionStateManager.this.mBtMessage, handle);
        }

        ConnectionGoal getConnectionGoal() {
            if (ConnectionStateManager.this.mBTAdapterEnabled) {
                return this.mPrivateGoal;
            }
            Trace.debug(ConnectionStateManager.TAG, "bluetooth disabled; discon forcing temp goal = DISCONNECT for " + this.mDeviceHandle);
            return ConnectionGoal.DISCONNECT;
        }

        private void setPrivateState(PrivateConnectionState newState) {
            Trace.debug(ConnectionStateManager.TAG, "setting private state for " + this.mDeviceHandle + " to " + newState.name());
            if (newState == PrivateConnectionState.DISCONNECTED) {
                ConnectionStateManager.this.actionRemoveEndpointSet(this.mDeviceHandle);
                RemoteDeviceInterface.logRemoteDeviceDisconnected();
            } else if (newState == PrivateConnectionState.CONNECTED) {
                ConnectionStateManager.this.actionDefaultEndpointSet(this.mDeviceHandle);
            } else if (newState == PrivateConnectionState.CONNECTED_PRF) {
                ConnectionStateManager.this.actionPrfEndpointSet(this.mDeviceHandle);
            }
            this.mPrivateState = newState;
            setPublicState();
        }

        private void setPublicState() {
            if ((this.mPrivateState == PrivateConnectionState.CONNECTED || this.mPrivateState == PrivateConnectionState.CONNECTED_PRF) && getConnectionGoal() == ConnectionGoal.CONNECT) {
                this.mPublicState = ConnectionStatus.CONNECTED;
            } else if (this.mPrivateState == PrivateConnectionState.CONNECTING || (getConnectionGoal() == ConnectionGoal.CONNECT && this.mPrivateState == PrivateConnectionState.DISCONNECTED)) {
                this.mPublicState = ConnectionStatus.CONNECTING;
            } else if (this.mPrivateState == PrivateConnectionState.DISCONNECTED) {
                this.mPublicState = ConnectionStatus.DISCONNECTED;
            }
            if (!this.mReconnectGracePeriodActive && this.mPublicState != this.mPublishedPublicState) {
                this.mPublishedPublicState = this.mPublicState;
                Trace.debug(ConnectionStateManager.TAG, "setting public status device = " + this.mDeviceHandle + " status = " + this.mPublishedPublicState);
                ConnectionStateManager.this.mConnectionStatusUpdater.onConnectionStatusUpdated(this.mDeviceHandle, this.mPublishedPublicState);
            }
        }

        private void setPrivateGoal(ConnectionGoal goal) {
            Trace.debug(ConnectionStateManager.TAG, "setting private goal for " + this.mDeviceHandle + " to " + goal.name());
            this.mPrivateGoal = goal;
            ConnectionStateManager.this.mConnectionGoalUpdater.onConnectionGoalUpdated(this.mDeviceHandle, goal);
        }

        public String toString() {
            return this.mDeviceHandle + " goal = " + this.mPrivateGoal.name() + " state = " + this.mPrivateState.name();
        }
    }

    public static class PublicConnectionStatusUpdater {
        private final ContentResolver mContentResolver;

        public PublicConnectionStatusUpdater(ContentResolver contentResolver) {
            this.mContentResolver = contentResolver;
        }

        void onConnectionStatusUpdated(PblDevice device, ConnectionStatus status) {
            ContentValues updatedValues = new ContentValues(2);
            updatedValues.put("connection_status", Integer.valueOf(status.getIntValue()));
            if (status == ConnectionStatus.CONNECTED) {
                updatedValues.put("last_connected_time", Long.valueOf(System.currentTimeMillis()));
            }
            PblDeviceModel.updateDevice(this.mContentResolver, device, updatedValues);
        }
    }

    public ConnectionStateManager(Looper looper, Context context, IDeviceConnector btConnection, IAdapterQuery btAdapter, IDeviceMessageSender btMessage, PublicConnectionStatusUpdater connectionStatusUpdater, ConnectionGoalUpdater connectionGoalUpdater, FrameworkState frameworkState) {
        Trace.debug(TAG, "ConnectionStateManager()");
        PblDeviceModel.setAllDevicesDisconnected(context.getContentResolver());
        if (looper == null) {
            throw new IllegalArgumentException("looper cannot be null");
        } else if (btConnection == null) {
            throw new IllegalArgumentException("btConnection cannot be null");
        } else if (btAdapter == null) {
            throw new IllegalArgumentException("btAdapter cannot be null");
        } else if (connectionStatusUpdater == null) {
            throw new IllegalArgumentException("connectionStatusUpdater cannot be null");
        } else if (connectionGoalUpdater == null) {
            throw new IllegalArgumentException("connectionGoalUpdater cannot be null");
        } else if (frameworkState == null) {
            throw new IllegalArgumentException("connectionGoalUpdater cannot be null");
        } else {
            this.mContext = context;
            this.mHandler = new Handler(looper);
            this.mBtConnection = btConnection;
            this.mBtAdapter = btAdapter;
            this.mBtMessage = btMessage;
            this.mFrameworkState = frameworkState;
            this.mConnectionStatusUpdater = connectionStatusUpdater;
            this.mContext.registerReceiver(this, new IntentFilter("com.getpebble.android.ACTION_BACKOFF_EXPIRED"));
            this.mConnectionGoalUpdater = connectionGoalUpdater;
            this.mBtAdapter.registerBluetoothAdapterCallback(this);
            this.mBtConnection.registerBluetoothConnectionCallback(this);
            this.mBTAdapterEnabled = this.mBtAdapter.getAdapterEnabled();
            List<PblDeviceRecord> connectGoalDevices = PblDeviceModel.getPblDeviceRecords(context.getContentResolver(), Query.CONNECTION_GOAL_CONNECT);
            if (connectGoalDevices != null) {
                for (PblDeviceRecord deviceRecord : connectGoalDevices) {
                    requestConnectToDevice(deviceRecord.pblDevice);
                }
            }
        }
    }

    public void destroy() {
        this.mBtAdapter.unregisterBluetoothAdapterCallback(this);
        this.mBtConnection.unregisterBluetoothConnectionCallback(this);
        this.mContext.unregisterReceiver(this);
        cancelBackoffCallbacks();
    }

    private Context getContext() {
        return this.mContext;
    }

    public synchronized void requestConnectToDevice(PblDevice device) {
        Trace.debug(TAG, "connectToDevice() = " + device);
        this.mMultipleHandshakeFailures = false;
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.debug(TAG, ".. creating state record for " + device);
            state = new PrivateState(device);
            this.mDeviceToPrivateStateMap.put(device, state);
        } else {
            Trace.debug(TAG, ".. previous state: " + state);
        }
        for (PblDevice otherDeviceReference : this.mDeviceToPrivateStateMap.keySet()) {
            if (!otherDeviceReference.equals(device)) {
                PrivateState otherState = (PrivateState) this.mDeviceToPrivateStateMap.get(otherDeviceReference);
                if (!(otherState == null || otherState.mPrivateGoal == ConnectionGoal.DISCONNECT)) {
                    Trace.debug(TAG, ".. setting other device " + otherDeviceReference + " goal to DISCONNECT");
                    otherState.setPrivateGoal(ConnectionGoal.DISCONNECT);
                }
            }
        }
        state.setPrivateGoal(ConnectionGoal.CONNECT);
        state.setPublicState();
        state.mBackoffPeriodIndex = 0;
        processState();
    }

    public synchronized void requestDisconnectFromDevice(PblDevice device) {
        Trace.debug(TAG, "disconnectFromDevice() = " + device);
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.warning(TAG, ".. no state record exists for " + device + ", so can't disconnect");
        } else {
            Trace.debug(TAG, ".. previous state: " + state);
            state.setPrivateGoal(ConnectionGoal.DISCONNECT);
            processState();
        }
    }

    public synchronized void requestStateProcessing() {
        processState(true);
    }

    private synchronized void processState() {
        processState(false);
    }

    private synchronized void processState(boolean ignoreBackoff) {
        Trace.info(TAG, "processState() ignoreBackoff = " + ignoreBackoff);
        boolean waitingForDisconnect = false;
        for (PblDevice deviceReference : this.mDeviceToPrivateStateMap.keySet()) {
            PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(deviceReference);
            if (state != null && state.getConnectionGoal() == ConnectionGoal.DISCONNECT) {
                switch (AnonymousClass2.$SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState[state.mPrivateState.ordinal()]) {
                    case SMTPMessage.RETURN_FULL /*1*/:
                        continue;
                    case SMTPMessage.RETURN_HDRS /*2*/:
                        waitingForDisconnect = true;
                        break;
                    case ListInfo.INDETERMINATE /*3*/:
                        actionCancelBackoff(deviceReference, true);
                        break;
                    case SMTPMessage.NOTIFY_DELAY /*4*/:
                        actionInternalDisconnect(deviceReference);
                        waitingForDisconnect = true;
                        break;
                    case R.styleable.WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance /*5*/:
                        waitingForDisconnect = true;
                        break;
                    case R.styleable.WalletFragmentStyle_maskedWalletDetailsBackground /*6*/:
                        actionInternalDisconnect(deviceReference);
                        waitingForDisconnect = true;
                        break;
                    case R.styleable.WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance /*7*/:
                    case Response.NO /*8*/:
                        actionInternalDisconnect(deviceReference);
                        waitingForDisconnect = true;
                        break;
                    case R.styleable.WalletFragmentStyle_maskedWalletDetailsLogoTextColor /*9*/:
                        waitingForDisconnect = true;
                        break;
                    default:
                        break;
                }
            }
        }
        if (!waitingForDisconnect) {
            for (PblDevice deviceHandle : this.mDeviceToPrivateStateMap.keySet()) {
                state = (PrivateState) this.mDeviceToPrivateStateMap.get(deviceHandle);
                if (state != null && state.getConnectionGoal() == ConnectionGoal.CONNECT) {
                    switch (AnonymousClass2.$SwitchMap$com$getpebble$android$framework$connectionstate$ConnectionStateManager$PrivateConnectionState[state.mPrivateState.ordinal()]) {
                        case SMTPMessage.RETURN_FULL /*1*/:
                            actionInternalConnect(deviceHandle);
                            break;
                        case SMTPMessage.RETURN_HDRS /*2*/:
                        case R.styleable.WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance /*5*/:
                        case R.styleable.WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance /*7*/:
                        case Response.NO /*8*/:
                            break;
                        case ListInfo.INDETERMINATE /*3*/:
                            if (!isBackoffExpired(deviceHandle) && !ignoreBackoff) {
                                actionProcessBackoff(deviceHandle);
                                break;
                            }
                            actionCancelBackoff(deviceHandle, false);
                            actionInternalConnect(deviceHandle);
                            break;
                            break;
                        case SMTPMessage.NOTIFY_DELAY /*4*/:
                            actionInitiateHandshake(deviceHandle);
                            break;
                        case R.styleable.WalletFragmentStyle_maskedWalletDetailsBackground /*6*/:
                            actionInternalDisconnect(deviceHandle);
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        Trace.debug(TAG, "waiting for disconnect; exiting state machine");
    }

    private void actionInternalConnect(PblDevice device) {
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "internalConnect() device state not found! device = " + device);
            return;
        }
        Trace.debug(TAG, "connect call for " + device);
        try {
            if (this.mBtConnection.connectToDevice(device)) {
                state.setPrivateState(PrivateConnectionState.CONNECTING);
                return;
            }
            Trace.info(TAG, "connect call failed: revert to DISCONNECT");
            if (this.mBTAdapterEnabled) {
                state.setPrivateGoal(ConnectionGoal.DISCONNECT);
            }
        } catch (IllegalArgumentException e) {
            Trace.warning(TAG, "error connecting", e);
            if (this.mBTAdapterEnabled) {
                state.setPrivateGoal(ConnectionGoal.DISCONNECT);
            }
        }
    }

    private void actionInternalDisconnect(PblDevice device) {
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "internalDisconnect() device state not found! device = " + device);
            return;
        }
        Trace.debug(TAG, "disconnect call for " + device);
        if (this.mBtConnection.disconnectFromDevice(device)) {
            state.setPrivateState(PrivateConnectionState.DISCONNECTING);
        }
    }

    private void actionInitiateHandshake(PblDevice device) {
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "initiateHandshake() device state not found! device = " + device);
            return;
        }
        Trace.debug(TAG, "actionInitiateHandshake: " + device);
        state.setPrivateState(PrivateConnectionState.HANDSHAKE_INITIATED);
        state.mMessageRouter.setCurrentEndpointSet(getHandshakeEndpointSet(state.mMessageRouter, getContext(), this, this.mFrameworkState));
    }

    HandshakeEndpointSet getHandshakeEndpointSet(MessageRouter router, Context context, IHandshakeResult handshakeResult, FrameworkState frameworkState) {
        return new HandshakeEndpointSet(router, context, handshakeResult, frameworkState);
    }

    private void actionProcessBackoff(PblDevice device) {
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "processBackoff() device state not found! device = " + device);
        } else if (state.mBackoffInitiated) {
            Trace.debug(TAG, "actionProcessBackoff (cont) for " + device);
        } else {
            long nowMillis = System.currentTimeMillis();
            Trace.debug(TAG, "actionProcessBackoff init for " + device + " period = " + BACKOFF_PERIODS_MILLIS[state.mBackoffPeriodIndex] + " ms");
            state.mBackoffExpiryTimeMillis = BACKOFF_PERIODS_MILLIS[state.mBackoffPeriodIndex] + nowMillis;
            state.mBackoffInitiated = true;
            cancelBackoffCallbacks();
            this.mHandler.postDelayed(this.sBackoffRunnable, BACKOFF_PERIODS_MILLIS[state.mBackoffPeriodIndex] + 5);
            AlarmManager am = (AlarmManager) this.mContext.getSystemService("alarm");
            Intent intent = new Intent("com.getpebble.android.ACTION_BACKOFF_EXPIRED");
            intent.setPackage(PACKAGE_NAME);
            this.mCurrentAlarmIntent = PendingIntent.getBroadcast(this.mContext, 0, intent, 0);
            long elapsedRealtimeAlarm = (SystemClock.elapsedRealtime() + BACKOFF_PERIODS_MILLIS[state.mBackoffPeriodIndex]) + 5;
            if (VERSION.SDK_INT < 19) {
                Trace.verbose(TAG, "Scheduling alarm using set()");
                am.set(2, elapsedRealtimeAlarm, this.mCurrentAlarmIntent);
            } else if (state.mBackoffPeriodIndex <= 5) {
                Trace.verbose(TAG, "Scheduling alarm using setExact()");
                am.setExact(2, elapsedRealtimeAlarm, this.mCurrentAlarmIntent);
            } else {
                Trace.verbose(TAG, "Scheduling alarm using setWindow()");
                long windowPeriod = BACKOFF_PERIODS_MILLIS[state.mBackoffPeriodIndex] / 5;
                if (windowPeriod > 60000) {
                    windowPeriod = 60000;
                }
                am.setWindow(2, elapsedRealtimeAlarm, elapsedRealtimeAlarm + windowPeriod, this.mCurrentAlarmIntent);
            }
            if (state.mBackoffPeriodIndex < BACKOFF_PERIODS_MILLIS.length - 1) {
                state.mBackoffPeriodIndex = state.mBackoffPeriodIndex + 1;
            }
        }
    }

    public void onReceive(Context context, Intent intent) {
        Trace.verbose(TAG, "onReceive alarm callback");
        cancelBackoffCallbacks();
        processState(false);
    }

    private void actionRemoveEndpointSet(PblDevice device) {
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "actionRemoveEndpointSet() device state not found! device = " + device);
            return;
        }
        Trace.debug(TAG, "actionRemoveEndpointSet: " + device);
        state.mMessageRouter.setCurrentEndpointSet(null);
    }

    private void actionDefaultEndpointSet(PblDevice device) {
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "actionDefaultEndpointSet() device state not found! device = " + device);
            return;
        }
        Trace.debug(TAG, "actionDefaultEndpointSet: " + device);
        state.mMessageRouter.setEndpointSetToDefault(getContext());
    }

    private void actionPrfEndpointSet(PblDevice device) {
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "actionPrfEndpointSet() device state not found! device = " + device);
            return;
        }
        Trace.debug(TAG, "actionPrfEndpointSet: " + device);
        state.mMessageRouter.setEndpointSetToPrf(getContext());
    }

    private boolean isBackoffExpired(PblDevice device) {
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "isBackoffExpired() device state not found! device = " + device);
            return false;
        } else if (!state.mBackoffInitiated || System.currentTimeMillis() < state.mBackoffExpiryTimeMillis) {
            return false;
        } else {
            return true;
        }
    }

    private void actionCancelBackoff(PblDevice device, boolean setStateDisconnected) {
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "cancelBackoff() device state not found! device = " + device);
            return;
        }
        Trace.debug(TAG, "actionCancelBackoff for " + device + " setStateDisconnected = " + setStateDisconnected);
        if (setStateDisconnected) {
            state.setPrivateState(PrivateConnectionState.DISCONNECTED);
        }
        cancelBackoffCallbacks();
        state.mBackoffInitiated = false;
    }

    private void cancelBackoffCallbacks() {
        this.mHandler.removeCallbacks(this.sBackoffRunnable);
        if (this.mCurrentAlarmIntent != null) {
            ((AlarmManager) this.mContext.getSystemService("alarm")).cancel(this.mCurrentAlarmIntent);
            this.mCurrentAlarmIntent = null;
        }
    }

    public synchronized void onDeviceConnectionResult(PblDevice device, ConnectionResult result) {
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "onDeviceConnectionResult() device state not found! device = " + device);
        } else {
            switch (AnonymousClass2.$SwitchMap$com$getpebble$android$bluetooth$device$ConnectionResult[result.ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    state.setPrivateState(PrivateConnectionState.LINK_ESTABLISHED);
                    break;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    state.setPrivateState(PrivateConnectionState.BACKOFF);
                    break;
                case ListInfo.INDETERMINATE /*3*/:
                    if (this.mBTAdapterEnabled) {
                        state.setPrivateGoal(ConnectionGoal.DISCONNECT);
                    }
                    state.setPrivateState(PrivateConnectionState.DISCONNECTED);
                    break;
                case SMTPMessage.NOTIFY_DELAY /*4*/:
                    if (this.mBTAdapterEnabled) {
                        state.setPrivateGoal(ConnectionGoal.DISCONNECT);
                    }
                    state.setPrivateState(PrivateConnectionState.DISCONNECTED);
                    break;
            }
            processState();
        }
    }

    public synchronized void onDeviceDisconnected(PblDevice device) {
        Trace.debug(TAG, "onDeviceDisconnected: " + device);
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "deviceDisconnectedCallback() device state not found! device = " + device);
        } else {
            Trace.debug(TAG, "EventDeviceDisconnected for " + device);
            state.setPrivateState(PrivateConnectionState.DISCONNECTED);
            state.mBackoffPeriodIndex = 0;
            processState();
        }
    }

    public synchronized void handshakeResult(PblDevice device, boolean success, boolean isRunningRecovery) {
        PrivateState state = (PrivateState) this.mDeviceToPrivateStateMap.get(device);
        if (state == null) {
            Trace.error(TAG, "Device state not found! device = " + device);
        } else if (state.mPrivateState != PrivateConnectionState.HANDSHAKE_INITIATED) {
            Trace.warning(TAG, "Handshake result received when not expected for " + device);
        } else {
            Trace.debug(TAG, "Handshake result for " + device + " success = " + success);
            if (success) {
                state.setPrivateState(isRunningRecovery ? PrivateConnectionState.CONNECTED_PRF : PrivateConnectionState.CONNECTED);
                this.mMultipleHandshakeFailures = false;
            } else {
                Trace.error(TAG, "Handshake failed: initiating disconnect");
                state.setPrivateState(PrivateConnectionState.HANDSHAKE_FAILED);
                if (this.mMultipleHandshakeFailures) {
                    Trace.info(TAG, "Multiple handshake failures; setting goal to DISCONNECT");
                    state.setPrivateGoal(ConnectionGoal.DISCONNECT);
                } else {
                    Trace.info(TAG, "First handshake failure; will retry");
                    this.mMultipleHandshakeFailures = true;
                }
            }
            processState();
        }
    }

    public synchronized void onAdapterStateChanged(boolean enabled) {
        Trace.debug(TAG, "onAdapterStateChanged() enabled = " + enabled);
        this.mBTAdapterEnabled = enabled;
        processState(true);
    }

    public synchronized void onAdapterError() {
        processState(true);
    }
}
